package com.scriptlib;

import android.media.Image;
import android.media.projection.MediaProjection;
import android.util.Log;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class AJFunc {
    private Object AjScreenCapturer;
    private Field MediaProjectionField;
    private Method AcquireLatestImageMethod;

    private Object AjConsole;
    private Method ConsoleLogMethod;

    /**
     * 版本号_以发布日期命名
     */
    static public String Version() {
        return "22.02.26";
    }

    static public String GetInfo() {
        return "https://gitee.com/yiszza/ScriptLib";
    }

    public MediaProjection GetMediaProjection() {
        try {
            return (MediaProjection) MediaProjectionField.get(AjScreenCapturer);
        } catch (IllegalAccessException e) {
            ConsoleLog(e.toString());
            return null;
        }
    }

    public Image AcquireLatestImage() {
        try {
            return (Image) AcquireLatestImageMethod.invoke(AjScreenCapturer);
        } catch (IllegalAccessException | InvocationTargetException e) {
            ConsoleLog(e.toString());
            return null;
        }
    }

    public void ConsoleLog(String msg) {
        try {
            ConsoleLogMethod.invoke(AjConsole, msg, null);
        } catch (IllegalAccessException | InvocationTargetException e) {
            Log.e("ScriptLib", e.toString());
        }
    }

    public AJFunc(Object obj) {
        try {
            Field imagesField = obj.getClass().getDeclaredField("images");
            imagesField.setAccessible(true);
            Object ajImages = imagesField.get(obj);

            Field screenCapturerField = ajImages.getClass().getDeclaredField("mScreenCapturer");
            screenCapturerField.setAccessible(true);
            AjScreenCapturer = screenCapturerField.get(ajImages);

            MediaProjectionField = screenCapturerField.getType().getDeclaredField("mMediaProjection");
            MediaProjectionField.setAccessible(true);

            AcquireLatestImageMethod = screenCapturerField.getType().getDeclaredMethod("acquireLatestImage");
            AcquireLatestImageMethod.setAccessible(true);

            Field consoleField = obj.getClass().getField("console");
            AjConsole = consoleField.get(obj);
            ConsoleLogMethod = consoleField.getType().getMethod("log", Object.class, Object[].class);

        } catch (IllegalAccessException | NoSuchFieldException | NoSuchMethodException e) {
            Log.e("ScriptLib", e.toString());
        }
    }
}
